package com.team9.fitness.controller;

import com.team9.fitness.entity.DietRecord;
import com.team9.fitness.service.DietRecordService;
import com.team9.fitness.service.ZRDDSDataExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 饮食记录管理控制器
 * 
 * 提供饮食记录和营养分析功能：
 * - 创建饮食记录：记录食物、用量、餐次、时间
 * - 营养分析：计算卡路里、蛋白质、脂肪、碳水化合物
 * - 查询记录：支持按日期、餐次类型筛选
 * - 食物信息：关联食物数据库，显示营养成分
 * 
 * 支持的餐次类型：
 * - 早餐、午餐、晚餐、加餐
 * - 支持自定义餐次类型
 */
@RestController
@RequestMapping("/api/diet-records")
@Slf4j
@CrossOrigin(origins = { "*" }, allowCredentials = "false")
public class DietRecordController {

    @Autowired
    private DietRecordService dietRecordService;

    @Autowired
    private ZRDDSDataExchangeService zrddsDataExchangeService;

    /**
     * 创建饮食记录
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createDietRecord(@RequestBody DietRecord dietRecord) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 验证必要字段
            if (dietRecord.getUserId() == null) {
                response.put("success", false);
                response.put("message", "用户ID不能为空");
                return ResponseEntity.ok(response);
            }

            if (dietRecord.getFoodId() == null) {
                response.put("success", false);
                response.put("message", "食物ID不能为空");
                return ResponseEntity.ok(response);
            }

            if (dietRecord.getAmount() == null || dietRecord.getAmount() <= 0) {
                response.put("success", false);
                response.put("message", "食用量必须大于0");
                return ResponseEntity.ok(response);
            }

            if (dietRecord.getMealTime() == null) {
                response.put("success", false);
                response.put("message", "用餐时间不能为空");
                return ResponseEntity.ok(response);
            }

            if (dietRecord.getMealType() == null || dietRecord.getMealType().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "餐次类型不能为空");
                return ResponseEntity.ok(response);
            }

            log.info("创建饮食记录: userId={}, foodId={}, amount={}, mealTime={}, mealType={}",
                    dietRecord.getUserId(), dietRecord.getFoodId(), dietRecord.getAmount(),
                    dietRecord.getMealTime(), dietRecord.getMealType());

            // 直接执行业务逻辑
            DietRecord createdRecord = dietRecordService.createDietRecord(dietRecord);
            response.put("success", true);
            response.put("message", "饮食记录创建成功");
            response.put("data", createdRecord);

            // 业务逻辑成功，发布数据到ZRDDS作为记录
            try {
                Map<String, Object> additionalData = new HashMap<>();
                additionalData.put("foodId", dietRecord.getFoodId());
                additionalData.put("amount", dietRecord.getAmount());
                additionalData.put("mealType", dietRecord.getMealType());
                additionalData.put("mealTime", dietRecord.getMealTime().toString());

                zrddsDataExchangeService.publishDietRecord("ADD_FOOD",
                        dietRecord.getUserId(), dietRecord.getId(), additionalData);
            } catch (Exception e) {
                log.warn("发布饮食记录数据到ZRDDS失败", e);
                // 不影响业务逻辑
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("创建饮食记录失败", e);
            response.put("success", false);
            response.put("message", "创建失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户的所有饮食记录
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getDietRecordsByUserId(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();

        try {
            List<DietRecord> records = dietRecordService.getDietRecordsByUserId(userId);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户饮食记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户指定日期的饮食记录
     */
    @GetMapping("/user/{userId}/date/{date}")
    public ResponseEntity<Map<String, Object>> getDietRecordsByUserIdAndDate(
            @PathVariable Long userId,
            @PathVariable String date) {
        Map<String, Object> response = new HashMap<>();

        try {
            LocalDateTime dateTime = LocalDateTime.parse(date + "T00:00:00");
            List<DietRecord> records = dietRecordService.getDietRecordsByUserIdAndDate(userId, dateTime);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户日期饮食记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户指定日期和餐次的饮食记录
     */
    @GetMapping("/user/{userId}/date/{date}/meal/{mealType}")
    public ResponseEntity<Map<String, Object>> getDietRecordsByUserIdAndMealTypeAndDate(
            @PathVariable Long userId,
            @PathVariable String date,
            @PathVariable String mealType) {
        Map<String, Object> response = new HashMap<>();

        try {
            LocalDateTime dateTime = LocalDateTime.parse(date + "T00:00:00");
            List<DietRecord> records = dietRecordService.getDietRecordsByUserIdAndMealTypeAndDate(userId, mealType,
                    dateTime);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户餐次饮食记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 获取用户指定日期的营养汇总
     */
    @GetMapping("/user/{userId}/summary/{date}")
    public ResponseEntity<Map<String, Object>> getDailyNutritionSummary(
            @PathVariable Long userId,
            @PathVariable String date) {
        Map<String, Object> response = new HashMap<>();

        try {
            LocalDateTime dateTime = LocalDateTime.parse(date + "T00:00:00");
            DietRecord summary = dietRecordService.getDailyNutritionSummary(userId, dateTime);
            response.put("success", true);
            response.put("data", summary);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取营养汇总失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据ID获取饮食记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getDietRecordById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();

        try {
            DietRecord record = dietRecordService.getDietRecordById(id);
            if (record != null) {
                response.put("success", true);
                response.put("data", record);
            } else {
                response.put("success", false);
                response.put("message", "饮食记录不存在");
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取饮食记录失败", e);
            response.put("success", false);
            response.put("message", "获取失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 更新饮食记录
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateDietRecord(@PathVariable Long id,
            @RequestBody DietRecord dietRecord) {
        Map<String, Object> response = new HashMap<>();

        try {
            dietRecord.setId(id);
            DietRecord updatedRecord = dietRecordService.updateDietRecord(dietRecord);
            response.put("success", true);
            response.put("message", "饮食记录更新成功");
            response.put("data", updatedRecord);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新饮食记录失败", e);
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 删除饮食记录
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteDietRecord(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();

        try {
            dietRecordService.deleteDietRecord(id);
            response.put("success", true);
            response.put("message", "饮食记录删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除饮食记录失败", e);
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 删除用户指定日期的所有饮食记录
     */
    @DeleteMapping("/user/{userId}/date/{date}")
    public ResponseEntity<Map<String, Object>> deleteDietRecordsByUserIdAndDate(
            @PathVariable Long userId,
            @PathVariable String date) {
        Map<String, Object> response = new HashMap<>();

        try {
            LocalDateTime dateTime = LocalDateTime.parse(date + "T00:00:00");
            dietRecordService.deleteDietRecordsByUserIdAndDate(userId, dateTime);
            response.put("success", true);
            response.put("message", "饮食记录删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除用户日期饮食记录失败", e);
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}
